package com.ulife.permission.manager.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.ulife.common.Result;
import com.ulife.common.exception.ManagerException;
import com.ulife.permission.common.RoleQueryResult;
import com.ulife.permission.dao.RoleDao;
import com.ulife.permission.dao.dataobject.RoleDO;
import com.ulife.permission.manager.RoleManager;

public class RoleManagerImpl implements RoleManager {
	
	@Autowired
	private RoleDao roleDao;

	public RoleQueryResult getAllRole() throws ManagerException {
		RoleQueryResult result = new RoleQueryResult();
		List<RoleDO> roleList;
		try {
			roleList = roleDao.getAllRole();
			if (CollectionUtils.isNotEmpty(roleList)) {
				result.setRoleList(roleList);
			}
			result.setSuccess(true);
			return result;
		} catch (SQLException e) {
			throw new ManagerException(e);
		}
	}

	public Result<RoleDO> addRole(RoleDO role) throws ManagerException {
		Result<RoleDO> result = new Result<RoleDO>();
		try {
			int id = roleDao.addRole(role);
			if (id > 0) {
				result.setSuccess(true);
				result.setModule(role);
			}
			return result;
		} catch (SQLException e) {
			throw new ManagerException(e);
		}
	}

	public Result<Integer> delRole(long roleId) throws ManagerException {
		Result<Integer> result = new Result<Integer>();
		try {
			int i = roleDao.delUser(roleId);
			if (i > 0) {
				result.setSuccess(true);
			}
			return result;
		} catch (SQLException e) {
			throw new ManagerException(e);
		}
	}

	public Result<Integer> updateRole(RoleDO role) throws ManagerException {
		Result<Integer> result = new Result<Integer>();
		try {
			int i = roleDao.updateUser(role);
			if (i > 0) {
				result.setSuccess(true);
			}
			return result;
		} catch (SQLException e) {
			throw new ManagerException(e);
		}
	}

	public Result<RoleDO> getRoleById(long roleId) throws ManagerException {
		Result<RoleDO> result = new Result<RoleDO>();
		try {
			RoleDO role = roleDao.getRoleById(roleId);
			if (role != null) {
				result.setSuccess(true);
				result.setModule(role);
			}
			return result;
		}catch (SQLException e) {
			throw new ManagerException(e);
		}
	}

	public RoleQueryResult getAllAvailableRoles() throws ManagerException {
		RoleQueryResult result = new RoleQueryResult();
		List<RoleDO> roleList;
		try {
			roleList = roleDao.getAllAvailableRoles();
			if (CollectionUtils.isNotEmpty(roleList)) {
				result.setRoleList(roleList);
			}
			result.setSuccess(true);
			return result;
		} catch (SQLException e) {
			throw new ManagerException(e);
		}
	}

}
